package main

import (
	"fmt"
	"os"

	"gitee.com/sweetsunnyflower/carpooling-server-go/app/commands"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/commands/make"

	_ "gitee.com/sweetsunnyflower/carpooling-server-go/app/requests/validators"
	"gitee.com/sweetsunnyflower/carpooling-server-go/bootstrap"
	bootstrapConfig "gitee.com/sweetsunnyflower/carpooling-server-go/config"

	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/config"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/console"
	"github.com/spf13/cobra"
)

func main() {
	// 应用的主入口，默认调用 cmd.CmdServe 命令
	var rootCmd = &cobra.Command{
		Use:   "Carpooling",
		Short: "小程序拼车服务端",
		Long:  `Default will run "serve" command, you can use "-h" flag to see all subcommands`,

		// rootCmd 的所有子命令都会执行以下代码
		PersistentPreRun: func(command *cobra.Command, args []string) {

			// 配置初始化，依赖命令行 --env 参数
			config.InitConfig(commands.Env)

			// 日志服务
			bootstrap.SetupLogger()

			// 启动数据库
			bootstrap.SetupDB()

			// 实例化app
			bootstrap.SetupApp()

			// 初始化 Redis
			bootstrap.SetupRedis()

			// 初始化缓存
			bootstrap.SetupCache()

			// 初始化websocket
			bootstrap.SetupWebsocket()
		},
	}

	// 注册子命令
	rootCmd.AddCommand(
		commands.CmdServe,
		commands.CmdKey,
		commands.CmdPlay,
		make.CmdMake,
		commands.CmdMigrate,
		commands.CmdDBSeed,
		commands.CmdCache,
		commands.CmdSyncVehicleBrand,
	)

	// 配置默认运行 Web 服务
	commands.RegisterDefaultCmd(rootCmd, commands.CmdServe)

	// 注册全局参数，--env
	commands.RegisterGlobalFlags(rootCmd)

	// 执行主命令
	if err := rootCmd.Execute(); err != nil {
		console.Exit(fmt.Sprintf("Failed to run app with %v: %s", os.Args, err.Error()))
	}
}

func init() {
	bootstrapConfig.Initialize()
}
